import { find, instantiate, Node, Prefab, resources, _decorator, game, sys, native, assetManager, director } from "cc";
import { UIManager } from "./AshFramework/Managers/UIManager";

export default class Banner {
    static TestMode: boolean = false;
    static NeedShowMoreAd: boolean = true;//true 显示广告
    static IsNative: boolean = false;
    static VibrateOn: boolean = true;//true 开启震动

    static Owner: string = `著作权人：北京玩伴同乐科技有限公司`;              //健康忠告-著作权人
    static License: string = `登记号：2022SRE011187`;                        //健康忠告-登记号
    static AgeLimit: number = 16;                                           //健康忠告-适龄

    Company = Company.厦门市灵玩网络科技有限公司;

    private _appId: string = "31409129";
    private _videoId: string = "680720219a2f43fd90d799fafb88cd8f";
    private _customId: string = "ab16dc38726044708a96b254b7ceda8d";
    private _bannerId: string = "45b0023f27354c679e568aae4e238cc0";

    private _year: number = 2024;
    private _month: number = 3;
    private _date: number = 8;
    private _hour: number = 18;

    private nativeAd = null;
    private bannerAd = null;
    private rewardedVideoAd = null;
    private customAd = null;
    private popupAdIndex: number = 0;

    ShowBannerAd() {
        console.log(`加载Banner`);
        if (Banner.TestMode) return;

        if (sys.platform === sys.Platform.OPPO_MINI_GAME) {
            this.CreateOPPOBannerAd();
        }
        if (sys.platform === sys.Platform.VIVO_MINI_GAME) {
            this.CreateVIVOBannerAd();
        }
        if (sys.platform === sys.Platform.HUAWEI_QUICK_GAME) {
            this.ShowHWBanner();
        }
        if (Banner.IS_ANDROID) {
            this.CreateAndroidBannerAd();
        }
    }

    ShowCustomAd(parent: Node = null) {
        console.log(`加载原生`);

        if (Banner.TestMode) return;

        if (!this.TimeManager(this._year, this._month, this._date, this._hour, 0)) return;

        if (Banner.IS_OPPO_MINI_GAME) {
            if (Banner.IsNative) {
                this.CreateNative(parent);
            } else {
                this.CreateOPPOCustomAd();
            }
        }
        if (Banner.IS_VIVO_MINI_GAME) {
            if (Banner.IsNative) {
                this.CreateNative(parent);
            } else {
                this.CreateVIVOCustomAd();
            }
        }
        if (Banner.IS_HUAWEI_QUICK_GAME) {
            if (Banner.IsNative) {
                this.CreateHWNative(parent);
            } else {
                this.CreateHWCustomAd();
            }
        }
        if (Banner.IS_ANDROID) {
            this.CreateAndroidCustomAd();
        }
    }

    ShowVideoAd(callback, args?: any) {
        console.log(`加载激励视频`);
        if (Banner.TestMode) {
            if (args) {
                callback(args)
            } else {
                callback();
            }
            return;
        }

        if (Banner.IS_OPPO_MINI_GAME) {
            this.CreateOPPORewardedVideoAd(callback, args);
        }
        if (Banner.IS_VIVO_MINI_GAME) {
            this.CreateVIVORewardedVideoAd(callback, args);
        }
        if (Banner.IS_HUAWEI_QUICK_GAME) {
            this.CreateHWVideo(callback, args);
        }
        if (Banner.IS_XIAOMI_QUICK_GAME) {
        }
        if (Banner.IS_BYTEDANCE_MINI_GAME) {
        }
        if (Banner.IS_ANDROID) {
            this.CreateAndroidRewardedVideoAd(callback, args);
        }
    }

    //**创建桌面图标 */
    CreateIcon(reward: Function = null) {
        console.log(`创建桌面图标`);

        if (Banner.IS_OPPO_MINI_GAME) {
            this.OPPOCreateIcon(reward);
        }
        if (Banner.IS_VIVO_MINI_GAME) {
            this.VIVIOCreateIcon(reward);
        }
    }

    //**手机震动 */
    VibrateShort(vibrateType: VibrateType = VibrateType.Heavy) {
        if (!Banner.VibrateOn) return;

        if (Banner.IS_OPPO_MINI_GAME) {
            this.OPPOVibrateShort(vibrateType);
        }
        if (Banner.IS_VIVO_MINI_GAME) {
            this.VIVOVibrateShort(vibrateType);
        }
    }

    //**手机震动 持续400ms */
    VibrateLong() {
        if (!Banner.VibrateOn) return;

        if (Banner.IS_OPPO_MINI_GAME) {
            this.OPPOVibrateLong();
        }
        if (Banner.IS_VIVO_MINI_GAME) {
            this.VIVOVibrateLong();
        }
    }

    //**开启原生自弹 */
    StartPopupAd(second: number = 30) {
        console.log(`开启原生自弹`);
        clearInterval(this.popupAdIndex);
        this.popupAdIndex = setInterval(this.ShowCustomAd.bind(this), 1000 * second);
    }

    StopPopupAd() {
        console.log(`关闭原生自弹`);
        clearInterval(this.popupAdIndex);
    }

    Quit() {
        console.log(`点击退出游戏`);

        if (sys.platform === sys.Platform.OPPO_MINI_GAME || sys.platform === sys.Platform.VIVO_MINI_GAME || sys.platform === sys.Platform.HUAWEI_QUICK_GAME) {
            //@ts-ignore
            qg.exitApplication({
                success: function () {
                    console.log("exitApplication success");
                },
                fail: function () {
                    console.log("exitApplication fail");
                },
                complete: function () { }
            });
        }

        if (Banner.IS_ANDROID) {
            this.AndroidQuit();
        }
    }

    //#region VIVO小游戏

    private CreateVIVOBannerAd() {
        if (!this.TimeManager(this._year, this._month, this._date, this._hour, 0)) return;

        try {
            if (!!this.bannerAd) this.bannerAd.destroy();
            this.bannerAd = null;

            //@ts-ignore
            this.bannerAd = qg.createBannerAd({
                posId: Banner.Instance._bannerId,
                style: {
                    //vivo
                    // left: view.getVisibleSize().width / 2 - 150,
                    // top: view.getVisibleSize().height + 150
                },
                adIntervals: 30
            });

            //加载监听事件
            this.bannerAd.onLoad(() => { console.log("Banner广告加载成功") });
            this.bannerAd.onSize(this.BannerOnSizeCallback);
            this.bannerAd.onError(e => console.log(`Banner出现错误：${JSON.stringify(e)}`));
            this.bannerAd.show();
        } catch (error) {
            console.log("Banner展示失败：" + error.message);
        }
    }

    private CreateVIVOCustomAd() {
        try {
            if (!!this.customAd) this.customAd.destroy();
            this.customAd = null;

            //@ts-ignore
            this.customAd = qg.createCustomAd({
                posId: Banner.Instance._customId,
                style: {
                    gravity: `center`
                }
            });

            this.customAd.onError(err => console.log(`原生广告出现错误：${JSON.stringify(err)}`));
            this.customAd.show().then(() => console.log('原生模板广告展示完成')).catch((err) => console.log('原生模板广告展示失败', JSON.stringify(err)));

        } catch (error) {
            console.log(error);
        }
    }

    private CreateVIVORewardedVideoAd(callback, args?: any) {
        try {
            if (!!this.rewardedVideoAd) this.rewardedVideoAd.destroy();
            this.rewardedVideoAd = null;

            //@ts-ignore
            this.rewardedVideoAd = qg.createRewardedVideoAd({
                posId: Banner.Instance._videoId,
            });

            this.rewardedVideoAd.load();

            this.rewardedVideoAd.onLoad((data) => {
                this.rewardedVideoAd.show();
                console.info('激励视频数据拉取成功: ', data);
            })

            this.rewardedVideoAd.onError((e) => {
                UIManager.ShowTip(`激励视频加载失败`);
                console.error(`激励视频出现错误：${JSON.stringify(e)}`);
            })

            this.rewardedVideoAd.onClose((res) => {
                if (res && res.isEnded) {
                    args ? callback(args) : callback();
                    console.log("正常播放结束，可以下发游戏奖励");
                } else console.log("播放中途退出，不下发游戏奖励");
            });
        } catch (error) {
            console.error(`激励视频异常信息：${error.message}`);
        }
    }

    private VIVIOCreateIcon(reward: Function) {
        //@ts-ignore
        qg.hasShortcutInstalled({
            success: function (status) {
                if (status) {
                    console.log(`已创建桌面图标`);
                } else {
                    //@ts-ignore
                    qg.installShortcut({
                        success: function () {
                            reward && reward();
                            console.log(`建桌面图标成功`);
                        }
                    })
                }
            }
        })
    }

    //触发较短时间震动，持续15ms
    private VIVOVibrateShort(vibrateType: VibrateType) {
        //@ts-ignore
        qg.vibrateShort({
            type: vibrateType,
            success: function (res) { console.log(`震动成功：${JSON.stringify(res)}`) },
            fail: function (res) { console.log(`震动失败：${JSON.stringify(res)}`) },
            complete: function (res) { },
        });
    }

    //触发较长时间震动，持续400ms
    private VIVOVibrateLong() {
        //@ts-ignore
        qg.vibrateLong()
    }

    //#endregion

    //#region OPPO小游戏

    private CreateOPPOBannerAd() {
        if (!this.TimeManager(this._year, this._month, this._date, this._hour, 0)) return;

        try {
            if (!!this.bannerAd) this.bannerAd.destroy();
            this.bannerAd = null;

            //@ts-ignore
            this.bannerAd = qg.createBannerAd({
                posId: Banner.Instance._bannerId,
                // style: {
                //     top: 300,
                //     left: 0,
                //     width: 900,
                //     height: 300
                // },
                adIntervals: 30
            });
            this.bannerAd.onLoad(() => { console.log("Banner广告加载成功") });
            this.bannerAd.onError(e => console.error(`Banner广告出现错误：${JSON.stringify(e)}`));
            this.bannerAd.onResize(this.BannerOnSizeCallback);
            this.bannerAd.show();

        } catch (error) {
            console.log("Banner展示失败：" + error.message);
        }
    }

    //版本号>=1094
    private CreateOPPOCustomAd() {
        try {
            if (!!this.customAd) this.customAd.destroy();
            this.customAd = null;

            //@ts-ignore
            this.customAd = qg.createCustomAd({
                posId: Banner.Instance._customId,
                style: {
                    //@ts-ignore
                    top: qg.getSystemInfoSync().screenHeight / 2 - 120,
                    // left: 0,
                    //@ts-ignore
                    // width: qg.getSystemInfoSync().screenWidth,
                },
            });

            this.customAd.onLoad(() => console.log(`原生广告加载成功`));
            this.customAd.onError(err => console.log(`原生广告出现错误：${JSON.stringify(err)}`));
            this.customAd.show().then(() => console.log('原生模板广告展示完成')).catch((err) => console.log(`原生广告出现错误：${JSON.stringify(err)}`));

        } catch (error) {
            console.log(error);
        }
    }

    private CreateOPPORewardedVideoAd(callback, args?: any) {
        try {
            if (!!this.rewardedVideoAd) this.rewardedVideoAd.destroy();
            this.rewardedVideoAd = null;

            //@ts-ignore
            this.rewardedVideoAd = qg.createRewardedVideoAd({ adUnitId: Banner.Instance._videoId, });

            this.rewardedVideoAd.load();

            this.rewardedVideoAd.onLoad((data) => {
                this.rewardedVideoAd.show();
                console.info('激励视频数据拉取成功: ', data);
            })

            this.rewardedVideoAd.onError((e) => {
                UIManager.ShowTip(`激励视频加载失败`);
                console.error(`激励视频出现错误：${JSON.stringify(e)}`);
            })

            this.rewardedVideoAd.onClose((res) => {
                console.log('视频广告关闭回调')
                if (res && res.isEnded) {
                    args ? callback(args) : callback();
                    console.log("正常播放结束，可以下发游戏奖励");
                } else {
                    console.log("播放中途退出，不下发游戏奖励");
                }
            });
        } catch (error) {
            console.error("激励视频异常信息：" + error.message);
        }
    }

    OPPOCreateIcon(reward: Function) {
        //@ts-ignore
        qg.hasShortcutInstalled({
            success: function (status) {
                // 判断图标未存在时，创建图标
                if (status == false) {
                    //@ts-ignore
                    qg.installShortcut({
                        success: function () {
                            reward && reward();
                            console.log(`创建桌面图标成功`);
                        },
                        fail: function (err) {
                            console.log(`创建桌面图标失败：${err}`);
                        },
                        complete: function () { }
                    })
                }
            },
            fail: function (err) {
                console.log(`创建桌面图标失败：${err}`);
            },
        })
    }

    //使手机发生较短时间的振动（20 ms）
    private OPPOVibrateShort(vibrateType: VibrateType) {
        console.log(vibrateType);
        //@ts-ignore
        qg.vibrateShort({
            type: vibrateType,
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
        });
    }

    //触发较长时间震动，持续400ms
    private OPPOVibrateLong() {
        //@ts-ignore
        qg.vibrateLong({
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
        });
    }

    //#endregion

    //#region HUAWEI小游戏

    private DestroyVideoAd() {
        try {
            //如果已经有了对象则先销毁对象
            console.log("rewardedVideoAd this.destroy", this.rewardedVideoAd);
            if (!(typeof this.rewardedVideoAd == "undefined") || this.rewardedVideoAd == null) {
                console.log("rewardedVideoAd this.destroy");
                this.rewardedVideoAd.offLoad();
                //this.rewardedVideoAd.offError();
                this.rewardedVideoAd.offClose();
                this.rewardedVideoAd.destroy();
                this.rewardedVideoAd = null;
            }
        }
        catch (error) {
            console.log("异常信息：" + error.message);
        }
    }

    private CreateHWVideo(callback, args?: any) {
        this.DestroyVideoAd();
        try {
            if (this.rewardedVideoAd == null) {
                //@ts-ignore
                this.rewardedVideoAd = qg.createRewardedVideoAd({
                    adUnitId: this._videoId,
                });

                this.rewardedVideoAd.load();
                this.rewardedVideoAd.onLoad((data) => {
                    this.rewardedVideoAd.show();
                    console.info('激励视频数据拉取成功: ', data);
                })
                this.rewardedVideoAd.onError((e) => {
                    UIManager.ShowTip(`激励视频加载失败`);
                    console.error('load ad error:' + JSON.stringify(e));
                    console.log('load ad error:' + e.errMsg, e.errCode);
                })
                this.rewardedVideoAd.onClose((res) => {
                    console.log('视频广告关闭回调')
                    if (res && res.isEnded) {
                        if (args) {
                            callback(args)
                        } else {
                            callback();
                        }
                        console.log("正常播放结束，可以下发游戏奖励");

                    } else {
                        console.log("播放中途退出，不下发游戏奖励");
                    }
                });
            } else {
                this.rewardedVideoAd.load();
            }
        } catch (error) {
            console.error("激励视频异常信息：" + error.message);
        }
    }

    HWGameLogin(successCallback, failCallback) {
        if (Banner.TestMode) {
            successCallback();
            return;
        }

        console.log(`HW游戏登陆...`);

        console.log(this._appId);
        //@ts-ignore
        qg.gameLoginWithReal({
            forceLogin: 1,
            appid: this._appId,
            success: (data) => {
                console.log(`HW游戏登陆成功：${JSON.stringify(data)}`);
                successCallback();
            },
            fail: (data, code) => {
                console.error(`HW游戏登陆失败：${data} -data：${data} -code：${code}`);
                //状态码为7004或者2012，表示玩家取消登录。
                //此时，建议返回游戏界面，可以让玩家重新进行登录操作。
                if (code == 7004 || code == 2012) {
                    console.log("玩家取消登录，返回游戏界面让玩家重新登录。")
                    failCallback();
                }
                //状态码为7021表示玩家取消实名认证。
                //在中国大陆的情况下，此时需要禁止玩家进入游戏。
                if (code == 7021) {
                    console.log("The player has canceled identity verification. Forbid the player from entering the game.")
                    game.end();
                }
            }
        });
    }

    private CreateHWCustomAd() {
        if (this.TimeManager(this._year, this._month, this._date, this._hour, 0)) {
            try {
                if (this.customAd == null) {
                    //@ts-ignore
                    this.customAd = qg.createCustomAd({
                        posId: this.nativeAd
                    });

                    this.customAd.onError(err => {
                        console.log("原生模板广告加载失败", JSON.stringify(err));
                    });
                    this.customAd.show().then(() => {
                        console.log('原生模板广告展示完成');
                    }).catch((err) => {
                        console.log('原生模板广告展示失败', JSON.stringify(err));
                    })

                }
            } catch (error) {
                console.log(error);
            }
        }
    }

    private ShowHWBanner() {
        try {
            console.log(`加载 HWBanner ...`);
            // this.DestroyOPPOBanner();

            //@ts-ignore
            var height = qg.getSystemInfoSync().safeArea.height;
            //@ts-ignore
            this.bannerAd = qg.createBannerAd({
                adUnitId: this._bannerId,
                style: {
                    top: height - 57,
                    left: 0,
                    height: 57,
                    width: 360,
                }
            });

            //加载监听事件
            this.bannerAd.onLoad();
            this.bannerAd.onClose();
            this.bannerAd.onError((e) => {
                const errCode = e.errCode
                const errMsg = e.errMsg
                console.error(`HWBanner 广告数据拉取失败:[${JSON.stringify(e)}]-[${errMsg}]-[${errCode}]`);
            });

            console.log(`加载 HWBanner 成功`);

            this.bannerAd.show();

        } catch (error) {
            console.error("Banner展示失败：" + error.message);
        }
    }

    //#endregion

    //#region 自渲染

    private dUnitVideoUrlList = null;       //广告视频
    private adUnitImgUrl = null;            //广告图片
    private adUnitAdid = null;              //广告标识，用于上报曝光与点击
    private adUnitCreativeType = null;      //获取广告类型，取值说明如下：
    private adUnitInteractionType = null;   //获取广告点击之后的交互类型
    private source = null;                  //广告来源
    private title = null;                   //广告标题
    private logoUrl = null;                 //广告标签图片
    private clickBtnTxt = null;             //点击按钮文本描述
    private yuansheng_Node = null;

    private CreateNative(parent: Node = null) {
        if (this.TimeManager(this._year, this._month, this._date, this._hour, 0)) {
            try {
                this.DestroyNative();

                //@ts-ignore
                this.nativeAd = qg.createNativeAd({
                    posId: Banner.Instance._customId,
                })
                this.nativeAd.load();
                this.nativeAd.onLoad((data) => {
                    try {
                        console.info('ad data loaded: ' + JSON.stringify(data))
                        // var _data = eval(JSON.stringify(data));
                        // BannerAd.adUnitVideoUrlList = _data.adList[0]
                        this.adUnitImgUrl = data.adList[0].imgUrlList[0];
                        this.adUnitAdid = data.adList[0].adId;
                        this.adUnitCreativeType = data.adList[0].creativeType;
                        this.adUnitInteractionType = data.adList[0].interactionType;
                        this.source = data.adList[0].source;
                        this.title = data.adList[0].title;
                        this.logoUrl = data.adList[0].logoUrl;
                        this.clickBtnTxt = data.adList[0].clickBtnTxt;

                        console.info('广告数据拉取成功: ' +
                            '图片路径', this.adUnitImgUrl + '\n',
                            '广告标识，adid', this.adUnitAdid + '\n',
                            '广告类型', this.adUnitCreativeType + '\n',
                            '广告点击之后的交互类型', this.adUnitInteractionType + '\n',
                            '广告来源', this.source + '\n',
                            '广告标题', this.title + '\n',
                            '广告标签图片', this.logoUrl + '\n',
                            '点击按钮文本描述', this.clickBtnTxt);

                        resources.load("Prefabs/UI/OppoCustomAd", Prefab, function (err, res) {
                            if (err) {
                                console.log("预制体不存在");
                                return;
                            }
                            if (Banner.Instance.yuansheng_Node != null) {
                                Banner.Instance.yuansheng_Node.destroy();
                            }
                            Banner.Instance.yuansheng_Node = instantiate(res);

                            if (parent) {
                                Banner.Instance.yuansheng_Node.parent = parent;
                            } else {
                                Banner.Instance.yuansheng_Node.parent = find("Canvas");
                            }
                        });
                    } catch (error) {
                        console.log(error);
                    }
                });
                this.nativeAd.onError((e) => {
                    console.log('load ad error:' + JSON.stringify(e));
                    console.log('广告数据拉取失败:' + e.errMsg, e.errCode);
                });
            }
            catch (error) {
                console.log("异常信息：" + error.message);
            }
        }
    }

    private CreateHWNative(parent: Node = null) {
        if (!this.TimeManager(this._year, this._month, this._date, this._hour, this._hour)) return;
        try {
            this.DestroyNative();

            console.log(`加载 HW原生自渲染...`);

            //@ts-ignore
            this.nativeAd = qg.createNativeAd({
                adUnitId: this._customId,
                style: {
                    left: 0,
                    top: 0
                }
            })
            this.nativeAd.load();
            this.nativeAd.onLoad((data) => {
                // var _data = eval(JSON.stringify(data));
                // BannerAd.adUnitVideoUrlList = _data.adList[0]
                this.adUnitImgUrl = data.adList[0].imgUrlList[0];
                this.adUnitAdid = data.adList[0].adId;
                this.adUnitCreativeType = data.adList[0].creativeType;
                this.adUnitInteractionType = data.adList[0].interactionType;
                this.source = data.adList[0].source;
                this.title = data.adList[0].title;
                this.logoUrl = data.adList[0].logoUrl;
                this.clickBtnTxt = data.adList[0].clickBtnTxt;

                // this.NativeImage.spriteFrame.setTexture = this.adUnitImgUrl;  
                // this.NativeImage.node.active = true;
                console.info('广告数据拉取成功: ' +
                    '图片路径', this.adUnitImgUrl + '\n',
                    '广告标识，adid', this.adUnitAdid + '\n',
                    '广告类型', this.adUnitCreativeType + '\n',
                    '广告点击之后的交互类型', this.adUnitInteractionType + '\n',
                    '广告来源', this.source + '\n',
                    '广告标题', this.title + '\n',
                    '广告标签图片', this.logoUrl + '\n',
                    '点击按钮文本描述', this.clickBtnTxt);

                resources.load("Prefabs/UI/OppoCustomAd", Prefab, function (err, res) {
                    console.log(`加载 HW原生自渲染预制体...`);
                    if (err) {
                        console.error(`HWNative 预制体不存在此路径:"HW/OppoCustomAd [${err}]"`);
                        return;
                    }
                    if (Banner.Instance.yuansheng_Node != null) {
                        Banner.Instance.yuansheng_Node.destroy();
                    }
                    Banner.Instance.yuansheng_Node = instantiate(res);
                    console.log(Banner.Instance.yuansheng_Node);
                    if (parent != null) {
                        Banner.Instance.yuansheng_Node.parent = parent;
                    } else {
                        Banner.Instance.yuansheng_Node.parent = find("Canvas");
                    }
                    Banner.Instance.yuansheng_Node.setPosition(0, 0, 0);
                    console.log(`加载 HW原生自渲染预制体成功`);
                    // Banner.Instance.yuansheng_Node.setSiblingIndex(0);
                    // Banner.Instance.yuansheng_Node.zIndex = 500;

                });
            });

            this.nativeAd.onError((e) => {
                const errCode = e.errCode
                const errMsg = e.errMsg
                console.error(`HW 自渲染广告数据拉取失败:[${JSON.stringify(e)}]-[${errMsg}]-[${errCode}]`);
            });

            console.log(`加载 HW原生自渲染成功`);
        } catch (error) {
            console.error("HW原生自渲染失败：" + error.message);

        }
    }

    private DestroyNative() {
        try {
            if (this.nativeAd != null) {

                this.nativeAd.offLoad();
                this.nativeAd.destroy();
                console.log("原生销毁：");
                // this.nativeAd.offError();
            } else {

                // this.nativeAd.offError();
            }
        }
        catch (error) {
            console.log("异常信息：" + error.message);
        }
    }

    //#endregion

    //#region 安卓

    private CreateAndroidBannerAd() {
        native.reflection.callStaticMethod("com/cocos/game/MainActivity", "openBanner", "()V");
    }

    private CreateAndroidCustomAd() {
        native.reflection.callStaticMethod("com/cocos/game/MainActivity", "openInsert", "()V");
    }

    private CreateAndroidRewardedVideoAd(callback, args?: any) {
        native.reflection.callStaticMethod("com/cocos/game/MainActivity", "openVideo", "()V");
        //@ts-ignore
        window.rewardSuc = () => { callback && callback(args); }
    }

    private AndroidQuit() {
        native.reflection.callStaticMethod("com/cocos/game/MainActivity", "exit", "()V");
    }

    AndroidPrivacy() {
        console.log("点击隐私政策")

        if (Banner.IS_ANDROID) {
            native.reflection.callStaticMethod("com/cocos/game/MainActivity", "Hide", "()V");
        }
    }

    AndroidKeFu() {
        console.log("点击联系客服")

        if (Banner.IS_ANDROID) {
            native.reflection.callStaticMethod("com/cocos/game/MainActivity", "KeFu", "()V");
        }
    }

    AndroidMoreGame() {
        console.log("点击更多精彩")

        if (Banner.IS_ANDROID) {
            native.reflection.callStaticMethod("com/cocos/game/MainActivity", "MoreGame", "()V");
        }
    }

    //#endregion

    //#region 事件回调

    private BannerOnSizeCallback(data: any) {
        director.getScene()?.emit(Banner.CB_BannerOnSize, data);
    }

    //#endregion

    TimeManager(_year, _month, _date, _h, _m): boolean {
        var nowdate = new Date();
        var year = nowdate.getFullYear();           //年
        var month = nowdate.getMonth() + 1;         //月 获取当前月（注意：返回数值为0~11，需要自己+1来显示）
        var date = nowdate.getDate();               //日
        var day = nowdate.getDay();                 //周几
        var h = nowdate.getHours()                  //小时
        var m = nowdate.getMinutes()                //分钟
        var s = nowdate.getSeconds()                //秒

        if (year > _year) {
            return true
        } else if (year == _year) {
            if (month > _month) {
                return true;
            } else if (month == _month) {
                if (date > _date) {
                    return true;
                } else if (date == _date) {
                    if (h > _h) {
                        return true;
                    } else if (h == _h) {
                        if (m >= _m) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    SetCityIsWhite() {
        const IPAreas = ["石家庄", "太原市", "沈阳市", "长春市", "哈尔滨市", "南京市", "杭州市", "合肥市",
            "福州市", "南昌市", "济南市", "郑州市", "长沙市", "武汉市", "海口市", "成都市", "贵阳市", "昆明市",
            "西安市", "兰州市", "西宁市", "北京市", "天津市", "上海市", "重庆市", "大连市", "青岛市", "厦门市", "广东省"];

        if (Banner.IS_VIVO_MINI_GAME) {
            assetManager.loadRemote("https://yxapi.tomatojoy.cn/getIp", (err, res) => {
                let province = JSON.parse(res._nativeAsset).data.province;//省份
                let city = JSON.parse(res._nativeAsset).data.city;//城市

                for (let i in IPAreas) {
                    if (city == IPAreas[i] || province == IPAreas[i]) {
                        console.log(`当前地区：${IPAreas[i]}`);
                        Banner.NeedShowMoreAd = false;
                        return;
                    }
                }

                Banner.NeedShowMoreAd = true;
            });
        }
        if (Banner.IS_OPPO_MINI_GAME || Banner.IS_ANDROID) {
            let xhr = new XMLHttpRequest();
            xhr.open('get', 'https://yxapi.tomatojoy.cn/getIp', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send();
            xhr.onreadystatechange = () => {
                if (xhr.readyState == 4) {
                    if (xhr.status >= 200 && xhr.status < 400) {
                        let json = JSON.parse(xhr.responseText);
                        let data = json.data;

                        for (let i in IPAreas) {
                            if (data.city == IPAreas[i] || data.province == IPAreas[i]) {
                                console.log(`当前地区：${IPAreas[i]}`);
                                Banner.NeedShowMoreAd = false;
                                return;
                            }
                        }
                    }
                    else {
                        console.log({ code: -1, msg: '请求失败' })
                    }
                }
                Banner.NeedShowMoreAd = true;
            }

        }
    }

    //#region 静态

    private static _instance: any;
    public static get Instance(): Banner {
        if (Banner._instance == null) Banner._instance = new Banner();
        return Banner._instance;
    }

    static CB_BannerOnSize = "CB_BannerOnSize";

    static get IS_ANDROID() { return sys.platform === sys.Platform.ANDROID; }
    static get IS_OPPO_MINI_GAME() { return sys.platform === sys.Platform.OPPO_MINI_GAME; }
    static get IS_VIVO_MINI_GAME() { return sys.platform === sys.Platform.VIVO_MINI_GAME; }
    static get IS_HUAWEI_QUICK_GAME() { return sys.platform === sys.Platform.HUAWEI_QUICK_GAME; }
    static get IS_XIAOMI_QUICK_GAME() { return sys.platform === sys.Platform.XIAOMI_QUICK_GAME; }
    static get IS_BYTEDANCE_MINI_GAME() { return sys.platform === sys.Platform.BYTEDANCE_MINI_GAME; }

    //#endregion


}

export enum VibrateType {
    Light = "light",
    Medium = "medium",
    Heavy = "heavy",
}

export enum Company {
    北京星光图讯科技有限公司 = "北京星光图讯科技有限公司",
    北京维商联行商业发展有限责任公司 = "北京维商联行商业发展有限责任公司",
    北京易网科技有限公司 = "北京易网科技有限公司",
    北京华澳擎海信息技术有限公司 = "北京华澳擎海信息技术有限公司",
    北京博恒通达信息科技有限公司 = "北京博恒通达信息科技有限公司",
    北京亚泰宏科电气有限公司 = "北京亚泰宏科电气有限公司",
    北京天智游信息技术有限公司 = "北京天智游信息技术有限公司",
    厦门歆阳网络科技有限公司 = "厦门歆阳网络科技有限公司",
    厦门市灵玩网络科技有限公司 = "厦门市灵玩网络科技有限公司",
    厦门市冰天信息科技有限公司 = "厦门市冰天信息科技有限公司",
    厦门市晨曦光年科技有限公司 = "厦门市晨曦光年科技有限公司",
    厦门大橙互娱科技有限公司 = "厦门大橙互娱科技有限公司",
    厦门玩聚网络科技有限公司 = "厦门玩聚网络科技有限公司",
    厦门冰柠科技有限公司 = "厦门冰柠科技有限公司",
    厦门泰酷文化科技有限公司 = "厦门泰酷文化科技有限公司",
    南京索润网络科技有限公司 = "南京索润网络科技有限公司",
    南京脉涌网络科技有限公司 = "南京脉涌网络科技有限公司",
    南京标越网络科技有限公司 = "南京标越网络科技有限公司",
    南京举手之劳贸易有限公司 = "南京举手之劳贸易有限公司",
    南京狐伦网络科技有限公司 = "南京狐伦网络科技有限公司",
    上海金馨科技有限公司 = "上海金馨科技有限公司",
    青岛大蜥蜴娱乐有限公司 = "青岛大蜥蜴娱乐有限公司",
}